

#include <omnetpp.h>
#include "VoIPApp.h"
#include "UDPBasicApp.h"
#include "UDPControlInfo_m.h"
#include "IPAddressResolver.h"

Define_Module(VoIPApp);
void VoIPApp::initialize(int stage)
{
    // because of IPAddressResolver, we need to wait until interfaces are registered,
    // address auto-assignment takes place etc.
    if (stage!=3)
        return;

    counter = 0;
    numSent = 0;
    numReceived = 0;
    // the only extra line added
    numDelayed =0;
    WATCH(numSent);
    WATCH(numReceived);
    arrivalSignal = registerSignal("arrival");
    localPort = par("localPort");
    destPort = par("destPort");

    const char *destAddrs = par("destAddresses");
    cStringTokenizer tokenizer(destAddrs);
    const char *token;
    while ((token = tokenizer.nextToken())!=NULL)
        destAddresses.push_back(IPAddressResolver().resolve(token));

    if (destAddresses.empty())
        return;

    bindToPort(localPort);

    cMessage *timer = new cMessage("sendTimer");
    scheduleAt((double)par("messageFreq"), timer);
}
void VoIPApp::finish()
{double globalLossRate = (double) (numSent - numReceived
        + numDelayed) / numSent;

    recordScalar("number of Packets sent", this->numSent);
    recordScalar("number of Packets received", this->numReceived);
    recordScalar("number of Packets Delayed ", this->numDelayed);
    recordScalar("loss Rate", globalLossRate);

}
void VoIPApp::handleMessage(cMessage *msg)
{
    if (msg->isSelfMessage())
    {
        // send, then reschedule next sending
        sendPacket();
        scheduleAt(simTime()+(double)par("messageFreq"), msg);
    }
    else
    {
        cPacket *thePacket = PK(msg);
                    simtime_t theArrivalTime = simTime().dbl();
                    simtime_t theTimestamp = (thePacket->getCreationTime().dbl());
                    emit(arrivalSignal, (theArrivalTime - theTimestamp));

                    if (theArrivalTime - theTimestamp > par("acceptedDelay")) {
                        numDelayed++;
                    }
        processPacket(PK(msg));
    }


}
